import webapp2
from google.appengine.ext import db
from google.appengine.api import users
from . import Item
from . import User

class Rating(db.Model):
	"""Represents a user's rating of a seller or item and the
	associated comments"""
	seller = db.UserProperty(required=True)
	rater = db.UserProperty(required=True)
	item = db.ReferenceProperty(Item.Item)
	rating = db.RatingProperty(required=True)
	comments = db.TextProperty()

	@classmethod
	def getRatings(cls, obj):
		q = cls.all()
		if isinstance(obj, Item.Item):
			q.filter('item =', obj)
		elif isinstance(obj, users.User):
			q.filter('seller =', obj)
			q.filter('item =', None)
		elif isinstance(obj, User.User):
			q.filter('seller =', obj.id)
			q.filter('item =', None)
		q.order('-rating')
		return q

	@webapp2.cached_property
	def rater_obj(self):
		return User.User.getUser(self.rater)
